#include "EventLoopThread.h"

EventLoopThread::EventLoopThread(const ThreadInitCallback& cb, const std::string& name)
    : loop_(nullptr)
    , exiting_(false)
    , thread_(std::bind(&EventLoopThread::threadFunc, this), name)
    , mutex_()
    , cond_()
    , callback_(cb)
{}

EventLoopThread::~EventLoopThread()
{
    exiting_ = true;
    if(loop_ != nullptr)
    {
        loop_->quit();
        thread_.join();
    }
}

// 开启事件循环并返回loop_
EventLoop* EventLoopThread::startLoop()
{
    thread_.start(); // 开启线程并执行线程函数threadFunc

    EventLoop* loop;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while(loop_ == nullptr)
        {
            cond_.wait(lock);
        }
        loop = loop_;
    }

    return loop;
}

// 下面这个方法是在单独的新线程里面运行的
void EventLoopThread::threadFunc()
{
    // 创建一个独立的EventLoop，和线程thread_一一对应(one loop per thread)
    EventLoop loop; 

    if(callback_)
    {
        callback_(&loop); // 初始化线程
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }

    // 开启事件循环：EventLoop loop  => Poller.poll
    loop.loop(); 
    
    // 事件循环结束
    std::unique_lock<std::mutex> lock(mutex_);
    loop_ = nullptr;
}